package com.xiaoxie.system.service.impl;

import com.xiaoxie.common.constant.Constants;
import com.xiaoxie.common.redis.RedisManager;
import com.xiaoxie.system.domain.DictType;
import com.xiaoxie.system.domain.DictValue;
import com.xiaoxie.system.mapper.DictTypeMapper;
import com.xiaoxie.system.mapper.DictValueMapper;
import com.xiaoxie.system.service.DictValueService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class DictValueServiceImpl implements DictValueService {

    @Resource
    private DictValueMapper dictValueMapper;
    @Resource
    private DictTypeMapper dictTypeMapper;
    @Resource
    private RedisManager redisManager;


    // 使用这个注解，确保redis先初始化，再执行initCache方法，防止序列化出现问题
    @EventListener(ApplicationReadyEvent.class)
    public void initCache() {
        log.info("初始化缓存...");

        List<DictType> allDictTypes = dictTypeMapper.getAllDictTypes();
        for (DictType dictType : allDictTypes) {
            List<DictValue> dictValues = dictValueMapper.getDictValuesByTypeId(dictType.getId());
            if (dictValues != null && !dictValues.isEmpty()) {
                redisManager.setValue(Constants.DICT_PREFIX + dictType.getType(), dictValues);
            }
        }
        log.info("初始化缓存完成！");
    }


    @Override
    public List<DictValue> selectDictValueByTypeId(Integer id) {
        String type = dictTypeMapper.getDictTypeById(id).getType();
        List<DictValue> dictValues = (List<DictValue>)redisManager.getValue(Constants.DICT_PREFIX + type);
        if (dictValues != null && !dictValues.isEmpty()) {
            return dictValues;
        }
        dictValues = dictValueMapper.getDictValuesByTypeId(id);
        if (dictValues != null && !dictValues.isEmpty()) {
            redisManager.setValue(Constants.DICT_PREFIX + type, dictValues);
        }
        return dictValues;
    }

    @Transactional
    @Override
    public void addDictValue(DictValue dictValue) {
        Integer typeId = dictValue.getTypeId();
        DictType dictType = dictTypeMapper.getDictTypeById(typeId);
        if (dictType == null) {
            throw new RuntimeException("字典类型不存在！");
        }
        DictValue db_dictValue = dictValueMapper.getDictValueByTypeIdAndValue(dictValue.getTypeId(), dictValue.getValue());
        if (db_dictValue != null) {
            throw new RuntimeException("字典值已经存在！");
        }
        dictValueMapper.insertDictValue(dictValue);
        redisManager.delete(Constants.DICT_PREFIX + dictType.getType());
        redisManager.setValue(Constants.DICT_PREFIX + dictType.getType(), dictValueMapper.getDictValuesByTypeId(typeId));
    }

    @Transactional
    @Override
    public void updateDictValue(DictValue dictValue) {
        Integer typeId = dictValue.getTypeId();
        DictType dictType = dictTypeMapper.getDictTypeById(typeId);
        if (dictType == null) {
            throw new RuntimeException("字典类型不存在！");
        }
        DictValue db_dictValue = dictValueMapper.getDictValueByTypeIdAndValue(dictValue.getTypeId(), dictValue.getValue());
        if(db_dictValue != null && db_dictValue.getId().equals(dictValue.getId())) {
            throw new RuntimeException("字典值已经存在！");
        }
        dictValueMapper.updateDictValue(dictValue);
        redisManager.delete(Constants.DICT_PREFIX + dictType.getType());
        redisManager.setValue(Constants.DICT_PREFIX + dictType.getType(), dictValueMapper.getDictValuesByTypeId(typeId));
    }

    @Transactional
    @Override
    public void deleteDictValueById(Integer id) {
        DictValue dictValue = dictValueMapper.getDictValueById(id);
        if (dictValue == null) {
            throw new RuntimeException("字典项不存在！");
        }
        String type = dictTypeMapper.getDictTypeById(dictValue.getTypeId()).getType();
        if (type == null) {
            throw new RuntimeException("字典类型不存在！");
        }
        dictValueMapper.deleteDictValueById(id);
        List<DictValue> dictValuesByTypeId = dictValueMapper.getDictValuesByTypeId(dictValue.getTypeId());
        if (dictValuesByTypeId == null || dictValuesByTypeId.isEmpty()) {
            redisManager.delete(Constants.DICT_PREFIX + type);
            return;
        }
        redisManager.delete(Constants.DICT_PREFIX + type);
        redisManager.setValue(Constants.DICT_PREFIX + type, dictValueMapper.getDictValuesByTypeId(dictValue.getTypeId()));
    }

    @Override
    public DictValue selectDictValueById(Integer id) {
        return dictValueMapper.getDictValueById(id);
    }

    @Override
    public void batchDeleteDictValue(List<Integer> idArray) {
        for (Integer id : idArray) {
            DictValue dictValue = dictValueMapper.getDictValueById(id);
            if (dictValue == null) {
                throw new RuntimeException("字典项不存在！");
            }
            String type = dictTypeMapper.getDictTypeById(dictValue.getTypeId()).getType();
            if (type == null) {
                throw new RuntimeException("字典类型不存在！");
            }
            dictValueMapper.deleteDictValueById(id);
            List<DictValue> dictValuesByTypeId = dictValueMapper.getDictValuesByTypeId(dictValue.getTypeId());
            if (dictValuesByTypeId == null || dictValuesByTypeId.isEmpty()) {
                redisManager.delete(Constants.DICT_PREFIX + type);
                return;
            }
            redisManager.delete(Constants.DICT_PREFIX + type);
            redisManager.setValue(Constants.DICT_PREFIX + type, dictValueMapper.getDictValuesByTypeId(dictValue.getTypeId()));
        }
    }
}
